"""统一响应渲染器"""
from rest_framework.renderers import JSONRenderer
from django.utils import timezone

class StandardJSONRenderer(JSONRenderer):
    """标准JSON响应渲染器 - 自动包装所有响应为统一格式"""

    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        渲染响应数据为统一格式

        注意：分页响应已经是统一格式，不需要再次包装
        """
        response = renderer_context.get('response') if renderer_context else None

        if response is None:
            return super().render(data, accepted_media_type, renderer_context)

        # 检查是否已经是统一格式（来自ApiResponseMixin或分页器）
        if isinstance(data, dict) and 'code' in data and 'message' in data:
            return super().render(data, accepted_media_type, renderer_context)

        # 包装为统一格式
        status_code = response.status_code

        # 根据状态码确定消息
        if 200 <= status_code < 300:
            message = "操作成功"
        elif status_code == 400:
            message = "请求参数错误"
        elif status_code == 401:
            message = "未授权"
        elif status_code == 403:
            message = "权限不足"
        elif status_code == 404:
            message = "资源不存在"
        elif status_code >= 500:
            message = "服务器内部错误"
        else:
            message = "操作完成"

        wrapped_data = {
            'code': status_code,
            'message': message,
            'data': data,
            'timestamp': timezone.now().isoformat()
        }

        return super().render(wrapped_data, accepted_media_type, renderer_context)
